package com.chenwei.rabbit.singleQueue;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author: chenwei
 * @date: 2021/3/30 17:52
 */
public class Customer {

    public static void main(String[] args) throws IOException, TimeoutException {
        //创建mq的连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置连接的mq主机
        //设置端口号
        connectionFactory.setPort(5672);
        connectionFactory.setHost("127.0.0.1");
        //设置连接的虚拟主机
        connectionFactory.setVirtualHost("/study");
        //设置用户信息
        connectionFactory.setUsername("chenwei");
        connectionFactory.setPassword("chenwei");
        //获取连接对象
        Connection connection = connectionFactory.newConnection();
        //获取连接中通道
        Channel channel = connection.createChannel();

        channel.queueDeclare("study",true,false,false,null);
        //消费消息
        //参数1：消费的队列
        //参数2：消费的自动确认机制
        //参数3: 消费是时的回调接口
        channel.basicConsume("study",true,new DefaultConsumer(channel){

            //最后一个参数，消息队列中取出的消息
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(new String(body));
            }
        });
    }

//    @Test
//    public void customer() throws IOException, TimeoutException {
//
//    }
}
